/**
 * 使用前应该先导入 JQuery 和 JQueryUI
 */

$(function () {
	$(".button").button();
	// 菜单 hover
	$(".menu_button").hover(function() {
		$(this).finish();
		$(this).animate({backgroundColor: "green"}, 500);
	}, function() {
		$(this).animate({backgroundColor: "transparent"}, 300);
	});
	// 点击Logo
	$(".logo").click(function() {
	    location.href = "/QuickLifeServer/manage/main.jsp";
	});
	// Tooltip跟踪鼠标 
	$(document).tooltip({
	    track: true
	});
});

// 为不足两位的数字加前面0
function addZero(num) {
	if (num < 10) {
		return "0" + num;
	} else {
		return num;
	}
}

// 重置父级 .login_form 内的所有 input_view
function resetInputView() {
	$(this).parents(".login_form").find(".input_view").val("");
}

function closeThisDialog() {
    $(this).dialog("close");
}

/**
 * 
 * @param success
 * @param fail
 */
function checkValidateCode(success, fail) {
	// 验证码验证
	$.post("validateCode", {'validateCode':$("#validate_code").val()}, function(data) {
		if (data.validateCode == false) {
			return fail();
		} else {
			return success();
		}
	}, "JSON");
}

/**
 * 刷新验证码
 * @param img 验证码显示的 img
 */
function flushValidateCode(img) {
	$(img).attr("src", "/QuickLifeServer/validateCode?t=" + new Date().getMilliseconds());
}

/**
* @Param JQuery对象，验证失败数据对应的组件
*/
function invalidEffect(component) {
	component.effect("pulsate", 500);
}

/**
 * 对象转字符串
 * @param {} obj 
 */
function obj2JSON(obj) {
	var json = "{";
	for (var param in obj) {
		var val = obj[param];
		if (typeof val == "number") {
			json = json + "'" + param + "':" + val + ",";
		} else if (typeof val == "boolean") {
			json = json + "'" + param + "':" + val + ",";
		} else if (typeof val == "string") {
			json = json + "'" + param + "':'" + val + "',";
		} else if (typeof val == "object") {
			json = json + obj2JSON(val);
		}
	}
	return json.substring(0, json.length - 1) + "}";
}

/**
* 图片预览
* @param view 用来显示图片的窗口JQuery对象
* @param img 图片
* @param measure 测量参数， 需要有width和height两个属性来限制大小
*/
function show_img(view, imgFile, measure) {
    var reader = new FileReader();
    reader.readAsDataURL(imgFile);
    reader.onload = function(e) {
	view.attr("src", e.target.result);
	if (measure) {
	    image_measure(view, measure.width, measure.height);
	}
    };
}

/**
* 图片预览
* @param prevView 用来预览图片的窗口id
* @param choice 选择框的id
* @param measure 测量参数， 需要有width和height两个属性来限制大小
*/
function image_prev(prevView, img, measure) {
	var select = false;
	// 遍历选择的文件
	var files = event.target.files;
	for (var i = 0, f; f = files[i]; i ++) {
		// 排除非图片选择
		if (!f.type.match('image.*')) {
			continue;
		}
		// 标志图片选择
		select = true;
		var reader = new FileReader();
		show_img($("#" + prevView, img, measure));
		reader.readAsDataURL(f);
	}
	if (!select) {
		$("#" + choice).val(null);
		invalidEffect($("#" + choice));
	}
}

/**
* 图片预览大小设置
* @param w 图片显示最大的宽度，默认400
* @param h 图片显示最大的高度， 默认260
*/
function image_measure(prevView, w, h) {
	var height = prevView.height();
	var width = prevView.width();
	var scaleW = (w == undefined ? 400 : w) / width;
	var scaleH = (h == undefined ? 260 : h) / height;
	var scale = scaleW < scaleH ? scaleW : scaleH;
	prevView.css("width", (scale * width));
}

/**
 * 设置Selector的数据
 * @param component 要设置的Selector的id
 */
function selectDataObtain(componentId) {
	var data = ["餐饮", "休闲娱乐", "生活服务", "购物", "酒店", "运动健身", "婚庆", "家居装修"];
	selectDataSet(data, componentId);
}

function selectDataSet(data, componentId) {
	for (var i = 0; i < data.length; i ++) {
		$("#" + componentId).append("<option id='" 
			+ data[i] + "' value = " + (i + 1) + ">" + data[i] + "</option>");
	}
}

/**
 * 得到表单对象
 * @param formContent 表单容器id
 * @returns {FormData}
 */
function getFormData(formContent) {
	var formData = new FormData();
	var input_view = $( "#" + formContent + " input.input_view:not('[type='file']')");
	for (var i = 0; i < input_view.length; i ++) {
	    if (input_view[i].value.length > 0 && input_view[i].name) {
		formData.append(input_view[i].name, 
			encodeURIComponent(input_view[i].value));
	    }
	}
	var select = $("#" + formContent + " select");
	for (var i = 0; i < select.length; i ++) {
	    if (select[i].value.length > 0 && select[i].name) {
		formData.append(select[i].name, 
			$(select[i]).find("option:selected").attr("value"));
	    }
	}
	var textarea = $("#" + formContent + "textarea");
	for (var i = 0; i < textarea.length; i ++) {
	    if (textarea[i].value.length > 0 && textarea[i].name) {
		formData.append(textarea[i].name, 
			encodeURIComponent(textarea[i].value));
	    }
	}
	// 地址
	formData.append("address", markerAddress);
	formData.append("lat", marker.getPosition().lat);
	formData.append("lon", marker.getPosition().lng);
	// 图片
	var fileInput = $("#" + formContent + " input[type='file']");
	if (fileInput) {
	    for (var i = 0; i < fileInput.length; i ++) {
		var files = fileInput[i].files;
		if (files) {
		    formData.append(fileInput[i].name, files[0]);
		}
	    }
	}
	
	return formData;
}

/**
 * html 通过 Ajax 上传表单数据
 * @param formData 表单数据对象，FormData类型对象可以用append方法添加表单数据
 * @param url 要上传的位置
 * @param success 上传完成后调用的方法
 * @param contentType 默认为 multipart/form-data
 */
function ajaxUpload(formData, url, success, contentType) {
	// XMLHttpRequest 对象构建
	var xhr = new XMLHttpRequest();
	xhr.open("POST", url, true);
	if (contentType) {
	    xhr.setRequestHeader("Content-type", contentType);
	} else {
	    xhr.setRequestHeader("Content-type", "multipart/form-data;");
	}
	xhr.onreadystatechange = function() {
	    if (xhr.readyState == 4) {
		success.call(this, xhr.responseText);
	    }
	};
	xhr.send(formData);
}

/*
* 加载框 
* Ajax overlay 1.0
* Author: Simon Ilett @ aplusdesign.com.au
* Descrip: Creates and inserts an ajax loader for ajax calls / timed events 
* Date: 03/08/2011 
*/
function ajaxLoader (el, options) {
	// Becomes this.options
	var defaults = {
		bgColor 		: '#fff',
		duration		: 800,
		opacity			: 0.7,
		classOveride 	: false
	};
	this.options 	= jQuery.extend(defaults, options);
	this.container 	= $(el);
	
	this.init = function() {
		var container = this.container;
		// Delete any other loaders
		this.remove(); 
		// Create the overlay 
		var overlay = $('<div></div>').css({
				'background-color': this.options.bgColor,
				'opacity':this.options.opacity,
				'width':container.width(),
				'height':container.height(),
				'position':'absolute',
				'top':'0px',
				'left':'0px',
				'z-index':99999
		}).addClass('ajax_overlay');
		// add an overiding class name to set new loader style 
		if (this.options.classOveride) {
			overlay.addClass(this.options.classOveride);
		}
		// insert overlay and loader into DOM 
		container.append(
			overlay.append(
				$('<div></div>').addClass('ajax_loader')
			).fadeIn(this.options.duration)
		);
    };
	
	this.remove = function(){
		var overlay = this.container.children(".ajax_overlay");
		if (overlay.length) {
			overlay.fadeOut(this.options.classOveride, function() {
				overlay.remove();
			});
		}	
	};

    this.init();
}	
	